import os,re
def finddummy(number):
    losetuplist=os.popen("losetup --list -O NAME,BACK-FILE").readlines()
    losetuplist=losetuplist[1:]
    for x in losetuplist:
        x = re.sub(r'\s+', '^', x)
        _result=x.split('^')
        if _result[0]=='/dev/loop'+number:
            return _result
    return None
def findmountpoint(dummy):
    dfList=os.popen("df -H|grep /dev/"+dummy).readlines()
    if len(dfList)==0:
        return None
    print(dummy)
    print(dfList)
    dfList=dfList[0]
    x = re.sub(r'\s+', '^', dfList)
    _result=x.split('^')
    if len(_result)>0:
        return _result[5]
    return None
out=["#!/bin/bash\n"]
deviceList=os.popen("ls -l /dev| egrep \"sd.*|hd.*\"|awk '{gsub(/,/,\"\");if ($5 == \"7\") print $6\",\"$10}'").readlines()
for x in deviceList:
    _result=x.split(',')
    _number=_result[0]
    _dummy=_result[1].replace("\n","")
    _same=finddummy(_number)
    if _same!=None:
        mountpoint=findmountpoint(_dummy)
        if mountpoint != None:
            out.append("mknod /dev/%s b 7 %s\n"%(_dummy,_number))
            out.append("mount -o auto,rw,loop=/dev/%s %s %s\n"%(_dummy,_same[1],mountpoint))
with open('auto.sh', 'w') as f:
    f.write("\n".join(out))
